package com.cskaoyan.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.ArrayList;
import java.util.Collection;


public class CustomAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        //断言不为空 否则抛出异常
        this.assertRealmsConfigured();

        //获得 realms
        Collection<Realm> originRealms = this.getRealms();

        //强转为我们自定义的 类型
        MallToken mallToken = (MallToken) authenticationToken;
        //根据 我们自定义的不同类型的realm 来分发
        String type = mallToken.getType(); //type 对应 我们定义的 两种 admin 和 wx
        ArrayList<Realm> realms = new ArrayList<>();
        for (Realm originRealm : originRealms) {
            if (originRealm.getName().toLowerCase().contains(type)){
                realms.add(originRealm);
            }
        }

        return realms.size() >= 1 ? this.doSingleRealmAuthentication(realms.iterator().next(),authenticationToken) :
                                    this.doMultiRealmAuthentication(realms,authenticationToken);
    }
}
